package com.horizon.common.converter;


import com.horizon.common.context.HorizonContext;
import com.horizon.common.vo.HorizonBaseVO;
import com.horizon.modules.system.entity.User;
import com.horizon.modules.system.service.IUserService;
import org.apache.commons.lang.time.FastDateFormat;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.BaseEntityWrapper;

import java.util.Date;
import java.util.Objects;

/**
 * 系统实体、视图、dto转换器.
 *
 * @author zhaoshb
 * @since 2022/12/4 21:21
 */
public abstract class HorizonBaseEvdConverter<E extends BaseEntity, V extends HorizonBaseVO, D> extends BaseEntityWrapper<E, V> {

    public abstract E dtoToEntity(D dto);

    public abstract V entityToVO(E entity);

    @Override
    public V entityVO(E entity) {
        V vo = entityToVO(entity);
        fillUserInfo(vo, entity);
        fillModifyTime(vo, entity);
        return vo;
    }

    private void fillUserInfo(V vo, E entity) {
        if (Objects.isNull(entity.getCreateUser())) {
            return;
        }
        String userName = getUserName(entity.getCreateUser());
        vo.setCreatorName(userName);
        vo.setCreatorId(entity.getCreateUser());
        if (Objects.equals(entity.getCreateUser(), entity.getUpdateUser())) {
            vo.setUpdaterName(userName);
        } else {
            vo.setUpdaterName(getUserName(entity.getUpdateUser()));
        }
        vo.setUpdaterId(entity.getUpdateUser());
    }

    private void fillModifyTime(V vo, E entity) {
        vo.setCreateTime(toTimeString(entity.getCreateTime()));
        vo.setUpdateTime(toTimeString(entity.getUpdateTime()));
    }

    private String toTimeString(Date date) {
        if (Objects.isNull(date)) {
            return null;
        }
        return FastDateFormat.getInstance().format(date);
    }

    private String getUserName(Long userId) {
        if (Objects.isNull(userId)) {
            return null;
        }
        IUserService userService = HorizonContext.getBean(IUserService.class);
        User user = userService.getBaseMapper().selectById(userId);
        return Objects.isNull(user) ? null : user.getName();
    }

}
